var http = require('../../utils/http.js');
const app = getApp()
var WxParse = require('../../libs/wxParse/wxParse.js');

Page({
  data: {
    current: 0,
    showSku: false,
    collectIcon: 'like-o',
    goods: {},
    skuTree: [],
    skuList: []
  },
  onLoad(options) {
    this.getGoodsData(options.id);
  },
  getGoodsData: function (id) {
    const userId = wx.getStorageSync('userId')
    wx.showLoading({
      title: '加载中',
    })
    const { skuTree, skuList } = this.data;
    var ths = this;
    var params = {
      url: "/api/goods/" + id,
      method: "GET",
      data: {
        userId: userId
      },
      callBack: function (res) {
        const goods = res.data
        WxParse.wxParse('goodsDetail', 'html', goods.detail, ths);
        // 凭借 sku 组件需要的数据格式
        goods.goodsAttrs.forEach(a => {
          // 获取sku tree
          const values = []
          a.attrValList.forEach(v => {
            if (v.pic) {
              values.push({ name: v.attrVal, image: v.pic });
            } else {
              values.push({ name: v.attrVal });
            }
          })
          skuTree.push({
            'k_s': a.attrId,
            'name': a.attrName,
            'values': values
          });
        })
        // 获取skuList
        goods.goodsSkus.forEach(s => {
          const sku = {
            id: s.id,
            price: s.price,
            stock: s.stock,
          }
          s.attrValIds.split(',').forEach((v, i) => {
            sku[Number(v.split(':')[0])] = s.attrVals.split(',')[i]
          })
          skuList.push(sku)
        })
        ths.setData({
          goods,
          skuTree,
          skuList
        });
        wx.hideLoading();
      }
    };
    http.request(params);
  },
  swiperChange: function (e) {
    var that = this;
    if (e.detail.source == 'touch') {
      that.setData({
        current: e.detail.current
      })
    }
  },
  onClickCart() {
    wx.switchTab({
      url: '/pages/cart/index',
      error: () => {
        wx.showToast({
          icon: 'none',
          title: '打开购物车失败',
        });
      },
    });
  },

  onClickUser() {
    wx.switchTab({
      url: '/pages/user/index',
      success: () => { },
      error: () => {
        wx.showToast({
          icon: 'none',
          title: '打开个人中心失败',
        });
      },
    });
  },

  onClickButton() {
    this.setData({ showSku: true });
  },
  showAttr() {
    // 打开属性选择
    this.setData({ showSku: true });
  },
  onCloseSku() {
    this.setData({ showSku: false })
  },

  /**
   * @desc 点击 sku 弹出层加入购物车
   * @param { Object } e.detail 选择的 sku 数据 { selectedCount, selectedSkuComb }
   */
  onSkuAddCart(e) {
    const skuId = e.detail.selectedSkuComb['id']
    const sku = this.data.goods.goodsSkus.find(e=> e.id == skuId)
    const userId = wx.getStorageSync('userId')
    const cartGood = {
      userId: userId,
      goodsId: sku.goodsId,
      num: e.detail.selectedCount,
      attrVals: sku.attrVals,
      attrValIds: sku.attrValIds
    }
    wx.showLoading();
    //加入购物车
    var params = {
      url: "/userApi/cart",
      method: "POST",
      data: cartGood,
      callBack: function(res) {
        wx.hideLoading();
        setTimeout( () => {
          wx.showToast({
            title: '加入成功',
            icon: "none",
          });
        },0);
      }
    };
    http.request(params);
  },

  /**
   * @desc 点击 sku 弹出层立即购买
   * @param { Object } e.detail 选择的 sku 数据 { selectedCount, selectedSkuComb }
   */
  onSkuBuy(e) {
    console.log(e)
  },
  onCollect(){
    const goods = this.data.goods
    goods.isCollect = !goods.isCollect
    this.setData({ goods });
    const userId = wx.getStorageSync('userId');
    var params = {
      url: "/userApi/"+userId+"/collect/"+goods.goodsId,
      method: "POST"
    };
    http.request(params);
  }
});